<template>
    <div>
         <!-- 面包屑导航 -->
         <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            <el-breadcrumb-item>权限列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row :gutter="20">
                    <el-button type="primary" @click="addRoleDialogVisible = true" >添加角色</el-button>
            </el-row>
            <el-table :data="roleList" border stripe >
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- 一级权限 -->
                        <el-row :class="['bdbottom',i1==0? 'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <el-col :span="5">
                                <el-tag closable >{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级和三级权限 -->
                            <el-col :span="19">
                                <el-row :class="[i2==0? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <!-- 二级权限 -->
                                    <el-col :span="6">
                                        <el-tag type="success" closable >{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 三级权限 -->
                                    <el-col :span="18" >
                                        <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)" >{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" align="center"></el-table-column>
                <el-table-column label="角色名称" prop="roleName" align="center"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                       <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditRoleDialog(scope.row.id)">编辑</el-button>
                       <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoleById(scope.row.id)">删除</el-button>
                       <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分配权限对话框 -->
        <el-dialog
            title="分配权限"
            :visible.sync="setRightdialogVisible"
            width="50%"
            @close="setRightDialogClosed">
            <!-- 树型控件 -->
           <el-tree
            :data="rightList"
            :props="treeProps"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="defKeys"
            ref="treeRef">

           </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加角色对话框 -->
        <el-dialog
            title="添加角色"
            :visible.sync="addRoleDialogVisible"
            width="50%"
            @close="addRoleDialogClosed">
                <el-form :model="addRoleForm" status-icon :rules="addRoleFormRules" ref="addRoleForm" label-width="80px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input  v-model="addRoleForm.roleName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addRoleForm.roleDesc" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改角色对话框 -->
        <el-dialog
            title="添加角色"
            :visible.sync="editRoleDialogVisible"
            width="50%"
            @close="editRoleDialogClosed">
                <el-form :model="editRoleForm" status-icon :rules="addRoleFormRules" ref="editRoleForm" label-width="80px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input  v-model="editRoleForm.roleName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="editRoleForm.roleDesc" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            roleList: [],
            setRightdialogVisible: false,
            rightList: [],
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            defKeys: [], // 默认选中的权限
            roleId: '',
            addRoleDialogVisible: false,
            addRoleForm: {
                roleName: '',
                roleDesc: ''
            },
            addRoleFormRules: {
               roleName: [
                  { required: true, message: '请输入角色名称', trigger: 'blur' }
               ],
               roleDesc: [
                  { required: true, message: '请输入角色描述', trigger: 'blur' }
               ]
            },
             editRoleDialogVisible: false,
             editRoleForm: {
                 roleName: '',
                 roleDesc: ''
             },
             editRoleId: ''
        }
    },
    created() {
        this.getRoleList()
    },
    methods: {
        async getRoleList() {
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
            this.roleList = res.data
           // console.log(this.roleList)
        },
        // 展示分配权限对话框
        async showSetRightDialog(row) {
            this.roleId = row.id
            // 获取权限列表
             const { data: res } = await this.$http.get('rights/tree')
             if (res.meta.status !== 200) return this.$message.error('获取权限树失败')
             this.rightList = res.data
             // 获取当天角色选中的权限
             this.getDefKeys(row, this.defKeys)
             this.setRightdialogVisible = true
        },

        // 根据Id删除对应的权限
        async removeRightById(role, rightId) {
            // 弹框提示用户是否要删除
            const confirmResult = await this.$confirm(
                '此操作将永久删除该文件, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
            if (confirmResult !== 'confirm') return this.$message.info('取消了删除！')
            const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if (res.meta.status !== 200) {
                return this.$message.error('删除权限失败！')
            }
            // this.getRoleList()
            role.children = res.data
        },
        // 通过递归获取默认选中的3级权限
        getDefKeys (node, arr) {
            // 如果当前 node 节点不包含 children 属性，则是三级节点
            if (!node.children) return arr.push(node.id)
            node.children.forEach(item => this.getDefKeys(item, arr))
        },
        // 监听分配权限对话框关闭
        setRightDialogClosed() {
            this.defKeys = []
        },
        // 分配权限
        async allotRights() {
            // 获取树形控件中所有选中的节点id
            const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
            // 将数组转为以,分隔的字符串
            const idsStr = keys.join(',')
           // console.log(idsStr)
           // console.log(this.roleId)
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idsStr })
            if (res.meta.status !== 200) return this.$message.error('权限分配失败')
            this.$message.success('分配权限成功！')
            this.getRoleList()
            this.setRightdialogVisible = false
        },
        // 添加角色
       async addRole() {
           this.$refs.addRoleForm.validate(async valid => {
               if (!valid) return this.$message.error('请填正确填写角色信息')
               const { data: res } = await this.$http.post('roles', this.addRoleForm)
               if (res.meta.status !== 201) return this.$message.error('添加角色失败')
               this.$message.success('添加角色成功')
               // 重新获取用户列表
               this.getRoleList()
                // 将对话框隐藏
               this.addRoleDialogVisible = false
           })
        },
        // 监听添加角色对话框的关闭
        addRoleDialogClosed() {
            this.$refs.addRoleForm.resetFields()
        },
        // 编辑角色信息
        async showEditRoleDialog(id) {
            // 根据id查询对应角色
           this.editRoleId = id
           const { data: res } = await this.$http.get('roles/' + id)
           if (res.meta.status !== 200) return this.$message.error('查询角色失败')
           this.editRoleForm = res.data
           this.editRoleDialogVisible = true
        },
        // 保存修改信息
        editRole() {
           this.$refs.editRoleForm.validate(async valid => {
               if (!valid) return this.$message.error('请填正确填写角色信息')
               const { data: res } = await this.$http.put('roles/' + this.editRoleId, this.editRoleForm)
               if (res.meta.status !== 200) return this.$message.error('修改角色失败')
               this.$message.success('修改角色成功')
               // 重新获取用户列表
               this.getRoleList()
                // 将对话框隐藏
               this.editRoleDialogVisible = false
           })
        },
        // 监听修改角色对话框的关闭
        editRoleDialogClosed() {
            this.$refs.editRoleForm.resetFields()
            this.editRoleForm = {}
        },
        // 根据id删除对应角色
        async deleteRoleById(id) {
            const confirmResult = await this.$confirm('请问是否要永久删除该角色, 是否继续?', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error)
            // 如果用户点击确认，则confirmResult 为'confirm'
            // 如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
            if (confirmResult !== 'confirm') return this.$message.info('已经取消删除')
            const { data: res } = await this.$http.delete('roles/' + id)
            // 判断如果删除失败，就做提示
            if (res.meta.status !== 200) return this.$message.error('删除角色失败')
            // 修改成功的提示
            this.$message.success('删除角色成功')
            // 重新请求最新的数据
             this.getRoleList()
        }

    }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>